package org.hdl.anima.session;

import static com.google.common.base.Preconditions.checkArgument;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.hdl.anima.Application;
import org.hdl.anima.common.IdentityFactory;
import org.hdl.anima.common.module.BasicModule;
import org.hdl.anima.proxy.ServerProxys;
import org.hdl.anima.transport.Channel;
/**
 * @author qiuhd
 * @since  2014-8-1
 * @version V1.0.0
 */
public class ClientSessionMgr extends BasicModule{
	
	private String serverId;
	private final Map<Integer, ClientSession> sessions = new ConcurrentHashMap<Integer, ClientSession>();
	private final SessionCloseListener listener = new ClientSessionCloseListener();
	private final static String SESSION_KEY = "session_key" ;
	
	public ClientSessionMgr(String moduleName) {
		super(moduleName);
	}
	
	@Override
	public void initialize(Application application) {
		super.initialize(application);
		this.serverId = application.getId();
	}

	public ClientSession createSession(Channel channel) {
		int identity = IdentityFactory.getInstance().getIdentity();
		ClientSession session = new ClientSession(serverId, identity, channel);
		session.setlistener(listener);
		channel.setAttribute(SESSION_KEY, session);
		sessions.put(identity, session);
		return session;
	}
	
	public static ClientSession getClientSession(Channel channel) {
		checkArgument(channel != null, "channel can not be null");
		return (ClientSession) channel.getAttribute(SESSION_KEY) ;
	}
	
	public ClientSession get(int identity) {
		return sessions.get(identity);
	}
	
	public void remove(int idetity) {
		sessions.remove(idetity);
	}
	
	public void remove(ClientSession session) {
		checkArgument(session != null,"Failed to remove session,cause : session is null");
		remove(session.getIdentity()) ;
	}
	
	/**
	 * Client session close listener
	 * @author qiuhd
	 */
	private class ClientSessionCloseListener implements SessionCloseListener {
		@Override
		public void onSessionClosed(Object session) {
			ClientSession clientSession = (ClientSession) session ;
			remove(clientSession);
		}
	}
}


